package com.lianqi.emcpframework.design.domain;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import com.lianqi.emcpframework.commons.bean.validate.ValidateBean;
import com.lianqi.emcpframework.design.annotation.Identity;

/**
 * @program emcp-framework
 * @ClassName Entity
 * @description: 领域实体定义
 * @author: sky
 * @create: 2018/11/21 11:06
 */
public interface Entity<T, ID> extends ValidateBean {

    /**
     * 获取主键ID
     * 
     * @return
     */
    default ID getId() {
        ID id = identity();
        return id;
    }

    /**
     * 判断当前对象和other是否为相同对象
     * 
     * @param other
     * @return
     */
    boolean sameIdentityAs(T other);

    /**
     * 返回实体的唯一标识 ID
     * 
     * @return
     */
    default ID identity() {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isPublic(field.getModifiers())) {
                field.setAccessible(true);
            }
            if (field.getAnnotation(Identity.class) != null) {
                try {
                    return (ID)field.get(this);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
